package com.cityfood.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cityfood.common.pojo.CityFoodResult;
import com.cityfood.common.pojo.UserDisplay;
import com.cityfood.common.utils.JuheUtils;
import com.cityfood.pojo.CfUser;
import com.cityfood.service.UserService;
import com.github.pagehelper.PageInfo;

/**
 * @author 
 *操作用户表
 */
@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/user",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getUserInfoByUserId(Integer userId){
		CityFoodResult cityFoodResult = new CityFoodResult();
		CfUser user = userService.getUserByUserId(userId);
		if (user!=null) {
			Map<String,Object> ms = new LinkedHashMap<String, Object>();
			ms.put("nickName", user.getNickname());
			ms.put("avatarUrl", user.getAvatarurl());
			ms.put("phone", user.getPhone());
			ms.put("collectNumber", user.getCollectNumber());
			ms.put("recordNumber", user.getRecordNumber());
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("查询用户信息成功");
			cityFoodResult.setData(ms);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("没有此用户信息");
		cityFoodResult.setData("{}");
		return cityFoodResult;
	}
	
	//根据用户手机号模糊查询所有用户
	@RequestMapping(value="/manage/userLikePhone",method=RequestMethod.GET)
	@ResponseBody
	public CityFoodResult getUserLikePhone(@RequestParam(defaultValue="")String phone,
										   @RequestParam(defaultValue="1")Integer currentPage){
		
		CityFoodResult cityFoodResult = new CityFoodResult();
		
		PageInfo<CfUser> userList = userService.getUserLikePhonePage(phone,currentPage);
		if (userList!=null) {
			List<UserDisplay> displays = new ArrayList<UserDisplay>();
			for (CfUser user : userList.getList()) {
				UserDisplay userDisplay = new UserDisplay();
				userDisplay.setId(user.getId());
				userDisplay.setNickName(user.getNickname());
				userDisplay.setAvatarUrl(user.getAvatarurl());
				userDisplay.setGender(user.getGender());
				userDisplay.setPhone(user.getPhone());
				userDisplay.setOpenId(user.getOpenid());
				userDisplay.setIsDisplay(user.getIsdisplay().intValue());
				displays.add(userDisplay);
			}
			Map<String,Object> mp = new LinkedHashMap<>();
			//存入查询到的总数
			mp.put("total", userList.getTotal());
			//存入需要展示的数据
			mp.put("users", displays);
			
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("查询用户信息成功");
			cityFoodResult.setData(mp);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("没有此用户信息");
		cityFoodResult.setData("{}");
		return cityFoodResult;
	}
	
	@RequestMapping(value="/user/bindPhone",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult updateUserBindPhone(HttpServletRequest req,Integer userId,String phone_number,String check_code){
		CityFoodResult cityfoodResult = new CityFoodResult();
		CfUser user = new CfUser();
		user.setId(userId);
		HttpSession session = req.getSession(false);
		String random = (String) session.getAttribute("checkCode");
		cityfoodResult.setCode(201);
		cityfoodResult.setData("{}");
		cityfoodResult.setMsg("未有验证码");
		if (random ==null || random =="") {
			cityfoodResult.setCode(201);
			cityfoodResult.setData("{}");
			cityfoodResult.setMsg("请先获取验证码");
		}else{
			if (random.equals(check_code)) {
				if (phone_number !=null && phone_number !="") {
					CfUser userByPhone = userService.getUserByPhone(phone_number);
					if (userByPhone!=null) {
					if (!userByPhone.getId().equals(user.getId())) {
						cityfoodResult.setMsg("电话号码已经存在");
						cityfoodResult.setCode(201);
						cityfoodResult.setData("{}");
						return cityfoodResult;
					}else{
						cityfoodResult.setMsg("您已绑定手机号码");
						cityfoodResult.setCode(200);
						cityfoodResult.setData("{}");
						return cityfoodResult;
					}
					}
				}
				user.setPhone(phone_number);
				int i = userService.updateUserBindPhone(user);
				if (i>0) {
					cityfoodResult.setMsg("手机号绑定成功");
					cityfoodResult.setCode(200);
					cityfoodResult.setData("{}");
				}else{
					cityfoodResult.setMsg("手机号绑定失败");
					cityfoodResult.setCode(201);
					cityfoodResult.setData("{}");
				}
			}
		}
		return cityfoodResult;
	}
	
	@RequestMapping(value="/user/getCheckCode",method=RequestMethod.POST)
	@ResponseBody
	public CityFoodResult getCheckCode(HttpServletRequest req,String phone){
		HttpSession session = req.getSession(false);
		CityFoodResult cityFoodResult = new CityFoodResult();
		String random = JuheUtils.sendTextMessage(phone);
		if (random !=null && random !="") {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("短信发送成功");
			cityFoodResult.setData(null);
			session.setAttribute("checkCode", random);
			removeSessionKeyOnTime(session,"checkCode", 1);
		}else{
			cityFoodResult.setCode(201);
			cityFoodResult.setMsg("短信发送失败，请检查网络");
			Map pams = new HashMap();
			pams.put("err_info", "第三方接口返回具体出错原因");
			cityFoodResult.setData(pams);
		}
		return cityFoodResult;
	}
	

	@RequestMapping(value="/user",method=RequestMethod.PUT)
	@ResponseBody
	public CityFoodResult updateUser(HttpServletRequest req,
			@RequestParam String nickName,
			@RequestParam String avatarUrl,
			@RequestParam String gender){
		
		HttpSession session = req.getSession(false);
		CityFoodResult cityFoodResult = new CityFoodResult();
		CfUser user = (CfUser)session.getAttribute("user");
		
		CfUser cfUser = userService.findUserByOpenid(user.getOpenid());
		
		cfUser.setNickname(nickName);
		cfUser.setAvatarurl(avatarUrl);
		cfUser.setGender(gender);
		int i = userService.updateUser(cfUser);
		if (i>0) {
			cityFoodResult.setCode(200);
			cityFoodResult.setMsg("修改用户信息成功");
			cityFoodResult.setData(true);
			return cityFoodResult;
		}
		cityFoodResult.setCode(201);
		cityFoodResult.setMsg("修改用户信息失败");
		cityFoodResult.setData(false);
		return cityFoodResult;
		
	}
	
	public final void removeSessionKeyOnTime(final HttpSession session,final String checkCode,int minutes){
		try {
		      //TimerTask实现1分钟后从session中删除checkCode
		      final Timer timer=new Timer();
		      timer.schedule(new TimerTask() {
		        @Override
		        public void run() {
		          session.removeAttribute(checkCode);
		          //System.out.println("checkCode删除成功");
		          timer.cancel();
		        }
		      },minutes*60*1000);
		    } catch (Exception e) {
		      e.printStackTrace();
		    }
	}
	
	

}
